package com.tencent.tbds.demo.hive;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.security.UserGroupInformation;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * usage:
 * java -cp  dev-demo-5.3.0.0.jar:$(echo /usr/hdp/2.2.0.0-2041/hive/lib/\*.jar | tr ' ' ':')::$(echo /usr/hdp/2.2.0.0-2041/hadoop/client/*.jar | tr ' ' ':'):/usr/hdp/2.2.0.0-2041/hadoop/hadoop-common.jar: com.tencent.tbds.demo.hive.HiveKerberosDemo --principal <principal> --keytab <keytab> --zk-list <host1:port1,host2:port2>
 *
 * java -cp  dev-demo-5.3.0.0.jar:$(echo /usr/hdp/2.2.0.0-2041/hive/lib/*.jar | tr ' ' ':'):$(echo /usr/hdp/2.2.0.0-2041/hadoop/client/*.jar | tr ' ' ':'): com.tencent.tbds.demo.hive.HiveKerberosDemo --principal liulv/tbds.instance@TBDS-F6FE11XH --keytab /tmp/liulv.keytab --zk-list tbds-10-206-0-53:2181
 */
public class HiveKerberosDemo {
    public static void main(String[] args) throws Exception {
        HiveKerberosDemoOption option = new HiveKerberosDemoOption(args);
        if (option.hasHelp()) {
            option.printHelp();
            return;
        }

        System.setProperty("java.security.krb5.conf", "/etc/krb5.conf");
        Configuration configuration = new Configuration();
        configuration.set("hadoop.security.authentication" , "Kerberos" );
        UserGroupInformation. setConfiguration(configuration);
        UserGroupInformation.loginUserFromKeytab(option.getPrincipal(), option.getKeytab());

        Class.forName("org.apache.hive.jdbc.HiveDriver");
        // String url = "jdbc:hive2://tbds-10-206-0-53:2181/;principal=hive/_HOST@TBDS-F6FE11XH;serviceDiscoveryMode=zooKeeper;zooKeeperNamespace=hiveserver2_default";
        //高可用方式：客户端选择可用的hiveserver
        String url = String.format("jdbc:hive2://%s/default;principal=hive/_HOST@TBDS-F6FE11XH;serviceDiscoveryMode=zooKeeper;zooKeeperNamespace=hiveserver2_default",
                option.getZkList());

        Connection conn = DriverManager.getConnection(url);
        Statement st = conn.createStatement();
        String sqlString = "SHOW DATABASES";
        ResultSet rs = st.executeQuery(sqlString);
        System.out.println("Show all databases in hive:");
        while (rs.next()) {
            System.out.println(rs.getString(1));
        }
        rs.close();
        st.close();
        conn.close();
    }
}
